<script lang="ts" setup name="LoginForm">
import { ref, watch } from 'vue'
import Message from '@/components/message/index'
import useStore from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { useField, useForm } from 'vee-validate'
import { useCountDown } from '@/utils/hooks'
import {
  accountRule,
  passwordRule,
  isAgreeRule,
  codeRule,
  mobileRule,
} from '@/utils/validate'
const { user } = useStore()
const router = useRouter()
const route = useRoute()
const { time, start } = useCountDown(60)

const type = ref<'account' | 'mobile'>('account')
// 表单校验  规则
const { validate, resetForm } = useForm({
  validationSchema: {
    account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule,
    mobile: mobileRule,
    code: codeRule,
  },
  // 提供初始值
  initialValues: {
    mobile: '13666666666',
    code: '123456',
    account: 'xiaotuxian001',
    password: '123456',
    isAgree: true,
  },
})
const { value: accountValue, errorMessage: accountError } =
  useField<string>('account')
const { value: passwordValue, errorMessage: passwordError } =
  useField<string>('password')
const { value: isAgreeValue, errorMessage: isAgreeError } =
  useField<boolean>('isAgree')
const {
  value: mobileValue,
  errorMessage: mobileError,
  validate: mobileValidate,
} = useField<string>('mobile')
const { value: codeValue, errorMessage: codeError } = useField<string>('code')
// console.log(useField('isAgree'))

// 登录按钮
const login = async () => {
  // 表单校验
  const res = await validate()
  // console.log(res)
  // 校验不通过，不发请求
  // if (!res.valid) return 由于两个表单校验都写在一起了，所以不能直接判断valid，不可能两个表单都填上，所以valid一直为false
  if (type.value === 'account') {
    if (res.errors.account || res.errors.password || res.errors.isAgree) return
    await user.login(accountValue.value, passwordValue.value)
  } else {
    if (res.errors.mobile || res.errors.code || res.errors.isAgree) return
    await user.mobileLogin(mobileValue.value, codeValue.value)
  }

  // console.log('通过校验，可以发送请求')

  try {
    //const path = (route.query.redirectUrl as string) || '/' 需要在路由导航守卫里传参数query，但是第三方登录不适合
    const path = localStorage.getItem('checkoutPath') || '/' //优先从本地存储里取路径
    localStorage.removeItem('checkoutPath') //需要清除掉本地存储
    router.push(path)
    // router.push('/')
    Message.success('登录成功')
  } catch {
    Message.error('用户名或密码错误，登录失败')
  }

  // 登录成功后，合并购物车
  const { cart } = useStore()
  cart.mergeLocalCart()
}
// 监听type的变化，当type变化时，重置表单
watch(type, () => {
  resetForm()
})

// 发送验证码
const mobileRef = ref<HTMLInputElement | null>(null)
const send = async () => {
  if (time.value > 0) return Message.error('不能重复发送') //如果倒计时没有结束，按钮点了没效果
  // 手机号表单校验
  const res = await mobileValidate()
  if (!res.valid) {
    mobileRef.value?.focus() //如果校验不通过，就让手机号表单自动获取焦点
    return
  }
  await user.sendMobileMsg(mobileValue.value)
  Message.success('获取验证码成功')
  start()
}
</script>
<template>
  <div class="account-box">
    <!-- 切换 -->
    <div class="toggle">
      <a href="javascript:;" v-if="type === 'mobile'" @click="type = 'account'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="type = 'mobile'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <!-- 账户登录表单 -->
      <template v-if="type === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              type="text"
              placeholder="请输入用户名或手机号"
              v-model="accountValue"
            />
          </div>
          <!-- 表单校验的提示 -->
          <div class="error" v-if="accountError">
            <i class="iconfont icon-warning" />{{ accountError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
              type="password"
              placeholder="请输入密码"
              v-model="passwordValue"
            />
          </div>
          <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />{{ passwordError }}
          </div>
        </div>
      </template>
      <!-- 验证码登录表单 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="mobileValue"
              ref="mobileRef"
            />
          </div>
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{ mobileError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input
              type="password"
              placeholder="请输入验证码"
              v-model="codeValue"
            />
            <span class="code" @click="send">{{
              time === 0 ? '发送验证码' : `${time}s后重新发送`
            }}</span>
          </div>
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{ codeError }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgreeValue"></XtxCheckbox>
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeError">
          <i class="iconfont icon-warning" />{{ isAgreeError }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      >
        <img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt=""
        />
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
